/*
 * Copyright (C) 2023 Coder.AN
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "udp.h"
#include <cstdlib>
#include <iostream>


void udp_callback(uint32_t size, uint8_t* buffer, udp::RecvInfo info)
{
    if (info.flag == FLAG_SUCCESS)
    {
        char src_ip[16];
        ip_to_str(src_ip, info.src_ip);
        std::cout << "From " << src_ip << ":" << info.src_port << ", size:" << size << std::endl;
        std::cout << "buffer:";
        for (int i = 0; i < size; i++) printf("%x ", buffer[i]);
        std::cout << std::endl;
    }
    else if (info.flag == FLAG_TIMEOUT)
    {
        std::cout << "Recv timeout." << std::endl;
    }
    else if (info.flag == FLAG_LOST)
    {
        std::cout << "Frame lost." << std::endl;
    }
    else if (info.flag == FLAG_ERROR)
    {
        std::cout << "Recv error." << std::endl;
    }
}

int main(int argc, char* argv[])
{
    udp::UDPReceiver udp_receiver;

    if (argc != 2)
    {
        std::cout << "usage: demo_udp_receiver <port>" << std::endl;
        return 0;
    }

    udp_receiver.set_listen_port(9999);
    udp_receiver.enable_async(udp_callback);

    if (!udp_receiver.init())
    {
        std::cout << "Can not init udp_receiver!" << std::endl;
        return 0;
    }

    while (1);
    return 0;
}